<template>
  <div class="profile">
    <!-- 导航栏 -->
    <NavBar
      title="个人中心"
      :left-arrow="false"
      class="profile__navbar"
    >
      <template #right>
        <van-icon name="setting-o" size="18" @click="onSettings" />
      </template>
    </NavBar>

    <!-- 用户信息 -->
    <div class="profile__header">
      <div class="profile__user">
        <div class="profile__avatar" @click="onAvatarClick">
          <img :src="userInfo.avatar" :alt="userInfo.name" />
          <div class="profile__avatar-edit">
            <van-icon name="camera-o" size="16" />
          </div>
        </div>
        <div class="profile__info">
          <h2 class="profile__name">{{ userInfo.name }}</h2>
          <p class="profile__desc">{{ userInfo.description || '这个人很懒，什么都没留下' }}</p>
          <div class="profile__badges">
            <span v-for="badge in userInfo.badges" :key="badge" class="profile__badge">
              {{ badge }}
            </span>
          </div>
        </div>
      </div>
      
      <!-- 学习统计 -->
      <div class="profile__stats">
        <div class="profile__stat" @click="onStatClick('courses')">
          <span class="profile__stat-value">{{ userStats.courseCount }}</span>
          <span class="profile__stat-label">学习课程</span>
        </div>
        <div class="profile__stat" @click="onStatClick('exams')">
          <span class="profile__stat-value">{{ userStats.examCount }}</span>
          <span class="profile__stat-label">参与考试</span>
        </div>
        <div class="profile__stat" @click="onStatClick('certificates')">
          <span class="profile__stat-value">{{ userStats.certificateCount }}</span>
          <span class="profile__stat-label">获得证书</span>
        </div>
        <div class="profile__stat" @click="onStatClick('points')">
          <span class="profile__stat-value">{{ userStats.points }}</span>
          <span class="profile__stat-label">学习积分</span>
        </div>
      </div>
    </div>

    <!-- 功能菜单 -->
    <div class="profile__content">
      <!-- 学习相关 -->
      <div class="profile__section">
        <h3 class="profile__section-title">学习管理</h3>
        <van-cell-group>
          <van-cell
            title="我的课程"
            icon="play-circle-o"
            is-link
            :value="`${userStats.courseCount}门`"
            @click="onMenuClick('my-courses')"
          />
          <van-cell
            title="学习记录"
            icon="clock-o"
            is-link
            @click="onMenuClick('study-records')"
          />
          <van-cell
            title="收藏夹"
            icon="star-o"
            is-link
            :value="`${userStats.favoriteCount}个`"
            @click="onMenuClick('favorites')"
          />
          <van-cell
            title="下载管理"
            icon="down"
            is-link
            @click="onMenuClick('downloads')"
          />
        </van-cell-group>
      </div>

      <!-- 考试相关 -->
      <div class="profile__section">
        <h3 class="profile__section-title">考试管理</h3>
        <van-cell-group>
          <van-cell
            title="我的考试"
            icon="edit"
            is-link
            :value="`${userStats.examCount}场`"
            @click="onMenuClick('my-exams')"
          />
          <van-cell
            title="考试成绩"
            icon="medal-o"
            is-link
            @click="onMenuClick('exam-results')"
          />
          <van-cell
            title="错题本"
            icon="question-o"
            is-link
            :value="`${userStats.wrongQuestionCount}题`"
            @click="onMenuClick('wrong-questions')"
          />
          <van-cell
            title="证书管理"
            icon="certificate"
            is-link
            :value="`${userStats.certificateCount}个`"
            @click="onMenuClick('certificates')"
          />
        </van-cell-group>
      </div>

      <!-- 账户相关 -->
      <div class="profile__section">
        <h3 class="profile__section-title">账户管理</h3>
        <van-cell-group>
          <van-cell
            title="个人资料"
            icon="contact"
            is-link
            @click="onMenuClick('profile-edit')"
          />
          <van-cell
            title="账户安全"
            icon="shield-o"
            is-link
            @click="onMenuClick('security')"
          />
          <van-cell
            title="消息通知"
            icon="bell"
            is-link
            :value="hasUnreadMessage ? '有新消息' : ''"
            @click="onMenuClick('notifications')"
          >
            <template #right-icon>
              <van-badge v-if="unreadCount > 0" :content="unreadCount" />
            </template>
          </van-cell>
          <van-cell
            title="隐私设置"
            icon="eye-o"
            is-link
            @click="onMenuClick('privacy')"
          />
        </van-cell-group>
      </div>

      <!-- 其他功能 -->
      <div class="profile__section">
        <h3 class="profile__section-title">其他功能</h3>
        <van-cell-group>
          <van-cell
            title="意见反馈"
            icon="comment-o"
            is-link
            @click="onMenuClick('feedback')"
          />
          <van-cell
            title="帮助中心"
            icon="question"
            is-link
            @click="onMenuClick('help')"
          />
          <van-cell
            title="关于我们"
            icon="info-o"
            is-link
            @click="onMenuClick('about')"
          />
          <van-cell
            title="检查更新"
            icon="upgrade"
            is-link
            :value="updateInfo.hasUpdate ? '有新版本' : '已是最新'"
            @click="onCheckUpdate"
          />
        </van-cell-group>
      </div>

      <!-- 退出登录 -->
      <div class="profile__section">
        <van-button
          type="danger"
          size="large"
          block
          @click="onLogout"
          class="profile__logout"
        >
          退出登录
        </van-button>
      </div>
    </div>

    <!-- 底部标签栏 -->
    <TabBar />

    <!-- 头像选择器 -->
    <van-action-sheet
      v-model:show="showAvatarSheet"
      :actions="avatarActions"
      @select="onAvatarSelect"
      cancel-text="取消"
    />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showDialog, showImagePreview } from 'vant'
import NavBar from '@/components/common/NavBar.vue'
import TabBar from '@/components/common/TabBar.vue'
import { useUserStore } from '@/stores/user'
import { useAppStore } from '@/stores/app'

const router = useRouter()
const userStore = useUserStore()
const appStore = useAppStore()

// 头像选择器
const showAvatarSheet = ref(false)
const avatarActions = [
  { name: '拍照', value: 'camera' },
  { name: '从相册选择', value: 'gallery' },
  { name: '查看大图', value: 'preview' }
]

// 用户信息
const userInfo = computed(() => userStore.userInfo)
const userStats = computed(() => userStore.userStats)

// 消息相关
const hasUnreadMessage = ref(true)
const unreadCount = ref(5)

// 更新信息
const updateInfo = reactive({
  hasUpdate: false,
  version: '1.0.0',
  newVersion: '1.0.1'
})

// 头像点击
const onAvatarClick = () => {
  showAvatarSheet.value = true
}

// 头像选择
const onAvatarSelect = (action) => {
  showAvatarSheet.value = false
  
  switch (action.value) {
    case 'camera':
      onTakePhoto()
      break
    case 'gallery':
      onSelectFromGallery()
      break
    case 'preview':
      onPreviewAvatar()
      break
  }
}

// 拍照
const onTakePhoto = () => {
  // 调用相机API
  showToast('拍照功能开发中')
}

// 从相册选择
const onSelectFromGallery = () => {
  // 调用相册API
  showToast('相册选择功能开发中')
}

// 预览头像
const onPreviewAvatar = () => {
  showImagePreview([userInfo.value.avatar])
}

// 统计点击
const onStatClick = (type) => {
  const routeMap = {
    courses: '/my-courses',
    exams: '/my-exams',
    certificates: '/my-certificates',
    points: '/points-detail'
  }
  
  if (routeMap[type]) {
    router.push(routeMap[type])
  }
}

// 菜单点击
const onMenuClick = (type) => {
  const routeMap = {
    'my-courses': '/my-courses',
    'study-records': '/study-records',
    'favorites': '/favorites',
    'downloads': '/downloads',
    'my-exams': '/my-exams',
    'exam-results': '/exam-results',
    'wrong-questions': '/wrong-questions',
    'certificates': '/my-certificates',
    'profile-edit': '/profile/edit',
    'security': '/profile/security',
    'notifications': '/notifications',
    'privacy': '/profile/privacy',
    'feedback': '/feedback',
    'help': '/help',
    'about': '/about'
  }
  
  if (routeMap[type]) {
    router.push(routeMap[type])
  } else {
    showToast('功能开发中')
  }
}

// 设置
const onSettings = () => {
  router.push('/settings')
}

// 检查更新
const onCheckUpdate = async () => {
  showToast('正在检查更新...')
  
  try {
    // 模拟检查更新
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    if (updateInfo.hasUpdate) {
      showDialog({
        title: '发现新版本',
        message: `发现新版本 ${updateInfo.newVersion}，是否立即更新？`,
        confirmButtonText: '立即更新',
        cancelButtonText: '稍后更新'
      }).then(() => {
        showToast('开始下载更新...')
      })
    } else {
      showToast('已是最新版本')
    }
  } catch (error) {
    showToast('检查更新失败')
  }
}

// 退出登录
const onLogout = () => {
  showDialog({
    title: '退出登录',
    message: '确定要退出登录吗？',
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(async () => {
    try {
      await userStore.logout()
      showToast('已退出登录')
      router.replace('/login')
    } catch (error) {
      showToast('退出失败')
    }
  })
}

// 页面初始化
onMounted(() => {
  // 检查是否有未读消息
  // checkUnreadMessages()
  
  // 检查应用更新
  // checkAppUpdate()
})
</script>

<style lang="scss" scoped>
@import '@/styles/variables.scss';
@import '@/styles/mixins.scss';

.profile {
  min-height: 100vh;
  background: $gray-50;
  padding-bottom: $tabbar-height;

  &__navbar {
    background: linear-gradient(135deg, $primary-color 0%, lighten($primary-color, 10%) 100%);
    color: white;
    
    :deep(.navbar__title-text) {
      color: white;
    }
    
    :deep(.van-icon) {
      color: white;
    }
  }

  &__header {
    background: linear-gradient(135deg, $primary-color 0%, lighten($primary-color, 10%) 100%);
    padding: $spacing-base $spacing-base $spacing-xl;
    color: white;
  }

  &__user {
    display: flex;
    align-items: center;
    margin-bottom: $spacing-xl;
  }

  &__avatar {
    position: relative;
    width: 80px;
    height: 80px;
    margin-right: $spacing-base;
    cursor: pointer;
    
    img {
      width: 100%;
      height: 100%;
      border-radius: 50%;
      border: 3px solid rgba(255, 255, 255, 0.3);
      object-fit: cover;
    }
  }

  &__avatar-edit {
    position: absolute;
    bottom: 0;
    right: 0;
    width: 24px;
    height: 24px;
    background: rgba(0, 0, 0, 0.6);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    
    .van-icon {
      color: white;
    }
  }

  &__info {
    flex: 1;
  }

  &__name {
    font-size: $font-size-xl;
    font-weight: $font-weight-bold;
    margin: 0 0 $spacing-xs 0;
  }

  &__desc {
    font-size: $font-size-sm;
    color: rgba(255, 255, 255, 0.8);
    margin: 0 0 $spacing-sm 0;
  }

  &__badges {
    display: flex;
    gap: $spacing-xs;
    flex-wrap: wrap;
  }

  &__badge {
    background: rgba(255, 255, 255, 0.2);
    color: white;
    padding: $spacing-xs $spacing-sm;
    border-radius: $border-radius-base;
    font-size: $font-size-xs;
  }

  &__stats {
    display: flex;
    justify-content: space-around;
    background: rgba(255, 255, 255, 0.1);
    border-radius: $border-radius-lg;
    padding: $spacing-base;
  }

  &__stat {
    text-align: center;
    cursor: pointer;
    transition: all $transition-duration-fast;
    
    &:active {
      transform: scale(0.95);
    }
  }

  &__stat-value {
    display: block;
    font-size: $font-size-xl;
    font-weight: $font-weight-bold;
    margin-bottom: $spacing-xs;
  }

  &__stat-label {
    font-size: $font-size-xs;
    color: rgba(255, 255, 255, 0.8);
  }

  &__content {
    padding: $spacing-base;
  }

  &__section {
    margin-bottom: $spacing-lg;
  }

  &__section-title {
    font-size: $font-size-base;
    font-weight: $font-weight-medium;
    color: $text-color;
    margin: 0 0 $spacing-base 0;
    padding: 0 $spacing-xs;
  }

  &__logout {
    margin-top: $spacing-xl;
    border-radius: $border-radius-xl;
  }
}

// 自定义单元格样式
:deep(.van-cell-group) {
  border-radius: $border-radius-lg;
  overflow: hidden;
  
  .van-cell {
    &::after {
      border-color: $border-color;
    }
    
    &:active {
      background: $gray-50;
    }
  }
  
  .van-cell__title {
    font-size: $font-size-base;
  }
  
  .van-cell__value {
    color: $text-color-light;
    font-size: $font-size-sm;
  }
  
  .van-cell__left-icon {
    color: $primary-color;
    margin-right: $spacing-sm;
  }
}

// 响应式适配
@include respond-below(480px) {
  .profile {
    &__header {
      padding: $spacing-sm $spacing-sm $spacing-lg;
    }
    
    &__user {
      margin-bottom: $spacing-lg;
    }
    
    &__avatar {
      width: 60px;
      height: 60px;
    }
    
    &__name {
      font-size: $font-size-lg;
    }
    
    &__stats {
      padding: $spacing-sm;
    }
    
    &__stat-value {
      font-size: $font-size-lg;
    }
    
    &__content {
      padding: $spacing-sm;
    }
  }
}
</style>